<template>
  <el-dialog
    :model-value="props.visible"
    :append-to-body="true"
    :destroy-on-close="true"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    width="1200px"
    :show-close="false"
    @close="emit('update:visible', false)"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <h4
          :id="titleId"
          :class="titleClass"
        >
          {{ dialogTitle }}
        </h4>
        <img
          src="@/assets/img/icon_guanbi.png"
          @click="close"
          class="close"
        />
      </div>
    </template>
    <div class="card-content">
      <div class="left">
        <Uploads
          ref="upload1"
          @change="setFileList"
          :listType="'picture-card'"
          :limit="1"
        >
        </Uploads>
        <div>270*180, jpg, png</div>
      </div>
      <div class="right">
        <el-form
          label-position="left"
          label-width="140px"
          label-suffix=": "
        >
          <div
            class="grid-2"
            style="column-gap: 40px"
          >
            <el-form-item :label="t('shipping.l1')">
              <el-input
                :maxlength="50"
                v-model="addForm.shippingName"
              ></el-input>
            </el-form-item>

            <el-form-item :label="t('shipping.l2')">
              <el-input
                :maxlength="50"
                v-model="addForm.shippingNo"
                @focus="openNumber($event, 'shippingNo')"
              ></el-input>
            </el-form-item>

            <el-form-item :label="t('shipping.l3')">
              <el-select
                v-model="addForm.shippingType"
                filterable
              >
                <el-option
                  v-for="child in dictData.ships_type"
                  :key="child.id"
                  :value="child.dictValue"
                  :label="child.dictLabel"
                  >{{ child.dictLabel }}</el-option
                >
              </el-select>
            </el-form-item>

            <!-- <el-form-item
                :label="t('shipping.l4')"
              >
                <el-input
                  :maxlength="50"
                  v-model="addForm.portRegistry"
                >
                </el-input>
              </el-form-item> -->

            <el-form-item :label="t('shipping.l5')">
              <el-select
                v-model="addForm.nationality"
                filterable
              >
                <el-option
                  v-for="child in countryOptionList"
                  :key="child.countryCode"
                  :value="child.countryName"
                  :label="child.countryName"
                  >{{ child.countryName }}</el-option
                >
              </el-select>
            </el-form-item>

            <el-form-item :label="t('shipping.l10')">
              <el-date-picker
                v-model="addForm.yearOfConstruction"
                type="year"
                value-format="YYYY"
                :placeholder="t('select_p')"
              />
            </el-form-item>

            <el-form-item :label="t('shipping.l6')">
              <el-select
                v-model="addForm.classificationSociety"
                filterable
              >
                <el-option
                  v-for="child in dictData.classification_society"
                  :key="child.id"
                  :value="child.dictValue"
                  :label="child.dictLabel"
                  >{{ child.dictLabel }}</el-option
                >
              </el-select>
            </el-form-item>

            <el-form-item :label="t('shipping.l9')">
              <el-input
                :maxlength="50"
                v-model="addForm.constructionPlant"
              ></el-input>
            </el-form-item>

            <el-form-item :label="t('shipping.l11')">
              <el-input
                :maxlength="50"
                v-model="addForm.deadweightTon"
                @input="inputNum('deadweightTon')"
                @focus="openNumber($event, 'deadweightTon')"
              >
                <template #suffix>MT</template>
              </el-input>
            </el-form-item>

            <el-form-item :label="t('shipping.l12')">
              <el-input
                :maxlength="50"
                v-model="addForm.totalLength"
                @input="inputNum('totalLength')"
                @focus="openNumber($event, 'totalLength')"
              >
                <template #suffix>M</template>
              </el-input>
            </el-form-item>

            <el-form-item :label="t('shipping.l18')">
              <el-input
                :maxlength="50"
                v-model="addForm.grossTon"
                @input="inputNum('grossTon')"
                @focus="openNumber($event, 'grossTon')"
              >
                <template #suffix>MT</template>
              </el-input>
            </el-form-item>

            <!-- <el-form-item
              :label="t('shipping.l13')"
            >
              <el-input
                :maxlength="50"
                v-model="addForm.lengthBetweenPerpendiculars"
                @input="inputNum('lengthBetweenPerpendiculars')"
                @focus="openNumber($event, 'lengthBetweenPerpendiculars')"
              ></el-input>
            </el-form-item> -->

            <el-form-item :label="t('shipping.l15')">
              <el-input
                :maxlength="50"
                v-model="addForm.model"
                @input="inputNum('model')"
                @focus="openNumber($event, 'model')"
              >
                <template #suffix>M</template>
              </el-input>
            </el-form-item>

            <el-form-item :label="t('shipping.l14')">
              <el-input
                :maxlength="50"
                v-model="addForm.moldedDepth"
                @input="inputNum('moldedDepth')"
                @focus="openNumber($event, 'moldedDepth')"
              >
                <template #suffix>M</template>
              </el-input>
            </el-form-item>

            <el-form-item :label="t('shipping.l7')">
              <el-input
                :maxlength="50"
                v-model="addForm.shipowner"
              ></el-input>
            </el-form-item>

            <el-form-item :label="t('shipping.l20')">
              <el-input
                :maxlength="50"
                v-model="addForm.host"
              ></el-input>
            </el-form-item>

            <el-form-item :label="t('shipping.l8')">
              <el-input
                :maxlength="50"
                v-model="addForm.shipManagement"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item
              :label="t('shipping.l16')"
            >
              <el-input
                :maxlength="50"
                v-model="addForm.draught"
                @input="inputNum('draught')"
                @focus="openNumber($event, 'draught')"
              ></el-input>
            </el-form-item>

            <el-form-item
              :label="t('shipping.l17')"
            >
              <el-input
                :maxlength="50"
                v-model="addForm.lightTon"
                @input="inputNum('lightTon')"
                @focus="openNumber($event, 'lightTon')"
              ></el-input>
            </el-form-item> -->

            <!-- <el-form-item
              :label="t('shipping.l19')"
            >
              <el-select
                v-model="addForm.electricalSystem"
                filterable
              >
                <el-option
                  v-for="child in dictData.electrical_system"
                  :key="child.id"
                  :value="child.dictValue"
                  :label="child.dictLabel"
                  >{{ child.dictLabel }}</el-option
                >
              </el-select>
            </el-form-item> -->
          </div>
        </el-form>

        <div
          class="number-keyboard"
          :style="numberModelStyle"
          v-if="numberShow"
        >
          <van-number-keyboard
            v-model="addForm[numberModelKey]"
            :show="numberShow"
            theme="custom"
            extra-key="."
            close-button-text="OK"
            @input="onInput"
            @blur="closeFn"
          />
          <el-button
            type="primary"
            @click="closeFn"
            class="close"
            >{{ t('cancelText') }}</el-button
          >
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer flexcc">
        <el-button
          plain
          color="#252628"
          @click="emit('update:visible', false)"
          >{{ t('cancelText') }}</el-button
        >
        <el-button
          type="primary"
          color="#252628"
          :loading="loading"
          @click="handleConfirm"
          >{{ t('confirmText') }}</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { uploads } from '@/service/common.js'
import { shippingListApi, addShippingApi, getShippingDetail, editShippingApi, deleteShipping } from '@/service/shipping'
import { countryListApi } from '@/service/common.js'
import useDict from '@/hooks/useDict'
import { useI18n } from 'vue-i18n'
import Uploads from '@/components/Uploads.vue'

const { t, locale } = useI18n()
const { dictData, getDictData } = useDict()

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  dialogType: {
    type: String,
    default: 'add'
  },
  editId: {
    type: [String, Number],
    default: null
  }
})

const dialogTitle = computed(() => {
  const obj = {
    add: t('shipping.b1'),
    edit: t('shipping.t2')
  }
  return obj[props.dialogType]
})

const emit = defineEmits(['update:visible'])

// 数字键盘
const numberModelKey = ref('')
const numberModelStyle = ref({
  top: '0px',
  left: '0px',
  background: 'none'
})
const numberShow = ref(false)
const openNumber = (e, key) => {
  // console.log(e, '==')
  const { top, left } = e.target.getBoundingClientRect()
  numberModelStyle.value = { top: `${top + 32}px`, left: `${left - 10}px`, background: '#f2f3f5' }
  numberShow.value = true
  numberModelKey.value = key
}
const onInput = (value) => {
  // console.log(value);
}
const closeFn = () => {
  numberShow.value = false
  numberModelStyle.value = {
    top: '0px',
    left: '0px',
    background: 'none'
  }

  numberModelKey.value = ''
}
const inputNum = (key) => {
  addForm.value[key] = addForm.value[key].replace(/[^\d.]/g, '')
}

//
const addForm = ref({
  enterpriseId: JSON.parse(localStorage.getItem('login')).userInfo.enterpriseId,
  picture: undefined
})
const upload1 = ref(null)
const FileList = ref([])

const setFileList = (val) => {
  FileList.value = val
}
const handleUpload = (ref, list) => {
  return new Promise((resolve, reject) => {
    const newList = list.value.filter((item) => item.raw)
    const oldList = list.value.filter((item) => !item.raw).map((item) => item.url)

    if (newList.length) {
      const formData = new FormData()
      newList.forEach((item) => {
        formData.append('files', item.raw)
      })
      uploads(formData).then(({ urls }) => {
        const resultFile = urls.split(',')
        list.value = resultFile.map((item) => {
          return {
            name: item.slice(item.lastIndexOf('/') + 1),
            url: item
          }
        })
        // ref.value.setFileList(list)
        resolve([...oldList, ...resultFile])
      })
    } else {
      resolve(oldList)
    }
  })
}

// 提交
const loading = ref(false)
const handleConfirm = async () => {
  loading.value = true
  let res = await handleUpload(upload1, FileList)
  // if (!res.length) {
  //   ElMessage.warning(t('shipping.w1'))
  //   return
  // }

  addForm.value.picture = res.join()

  const obj = {
    add: addShippingApi,
    edit: editShippingApi
  }

  obj[props.dialogType](addForm.value).then(({ msg }) => {
    ElMessage({
      message: msg,
      type: 'success'
    })
    emit('update:visible', false)
    emit('emitGetList')
  }).finally(()=>{
    setTimeout(() => {
      loading.value = false
    }, 1500);
  })
}

// 详情
const getDetail = () => {
  getShippingDetail(props.editId).then(({ data }) => {
    const { picture } = data
    addForm.value = data

    if (picture) {
      FileList.value = [
        {
          name: picture.slice(picture.lastIndexOf('/') + 1),
          url: picture
        }
      ]
    }
    upload1.value.setFileList(FileList.value)
  })
}

// 获取国家
const countryOptionList = ref([])

const init = () => {
  getDictData('ships_type') //船型
  getDictData('classification_society') //船级社
  getDictData('electrical_system') //电至
  countryListApi().then((res) => {
    countryOptionList.value = res.data
  })

  if (props.dialogType === 'edit') {
    getDetail()
  }
}
onMounted(() => {
  init()
})
</script>
<style scoped lang="scss">
// .body {
//     width: 100%;
//     background: rgba(245, 245, 245, 1);
//     padding-top: 30px;
//     padding-bottom: 130px;
//     margin-bottom: -80px;

//     .g-con {
//         .add-card {
//             .btn-list {
//                 display: flex;
//                 justify-content: end;
//             }
//         }

//         .card,
//         .add-card {
//             width: 100%;
//             padding-left: 34px;
//             min-height: 60px;
//             margin-top: 30px;

//             .card-header {
//                 display: flex;
//                 justify-content: space-between;
//                 align-items: center;

//                 .title {
//                     font-size: 20px;
//                     font-family: Microsoft YaHei;
//                     font-weight: bold;
//                     color: #ca2a02;
//                 }
//             }

//             :deep(.el-card__header) {
//                 border-bottom: 2px solid black;
//             }

//         }
//     }
// }
body {
  .el-overlay-dialog {
    .card-content {
      width: 100%;
      display: flex;

      .left {
        width: 272px;
        height: 100%;
        margin-right: 24px;
        padding-top: 32px;

        img {
          width: 100%;
          height: 180px;
        }
      }

      .right {
        flex: 1;
        padding-top: 32px;

        :deep(.el-descriptions__label),
        :deep(.el-form-item__label) {
          font-size: 12px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #9d9fa5;
          line-height: 24px;

          &::before {
            content: '*';
            color: red;
            margin-right: 2px;
          }
        }

        :deep(.my-label) {
          width: 140px;
          display: inline-block;
        }

        :deep(.el-descriptions__content),
        :deep(.el-form-item__content) {
          font-size: 12px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #252628;
          line-height: 24px;
        }

        .btn-list {
          margin-top: 20px;
          padding-left: 20px;
        }
      }
    }

    .number-keyboard {
      width: 100%;
      height: 270px;
      position: fixed;
      width: 273px;
      left: 0;
      top: 0;
      display: flex;
      flex-direction: column;
      align-items: center;

      :deep(.van-number-keyboard) {
        position: static;
        padding-bottom: 10px;
      }

      .close {
        width: 95%;
      }
    }
  }
}

.el-select {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;

  .el-input__inner {
    text-align: left;
  }
}

:deep(.el-date-editor.el-input) {
  width: 100%;

  .el-input__wrapper {
    width: 100%;
  }
}
</style>
